<!--
 * @Description: 柱图
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-11-15 10:49:23
 * @LastEditTime: 2021-12-15 17:18:46
 * @FilePath: \cscec-pms-admin\src\views\construction\constructionSchedule\components\EBar.vue
-->

<template>
  <a-row class="ear-box">
    <div ref="EBar" class="e-bar" :id="id" />
    <div class="zoom" v-if="zoom && eBarData.data[0].data.length > 7">
      <a-button class="zoom-btn" @click="zoomIn">+</a-button>
      <a-button class="zoom-btn" @click="zoomOut">-</a-button>
    </div>
    <div v-if="isSort && eBarData.data.length == 1" class="sort">
      <a-icon type="caret-up" @click="sortData('asc')" />
      <a-icon type="caret-down" @click="sortData('desc')" />
    </div>
  </a-row>
</template>

<script>
import elementResizeDetectorMaker from 'element-resize-detector'
export default {
  name: 'EBar',
  props: {
    // 图表选项
    eBarData: {
      type: Object,
      required: true
    },
    // 图表数据加载完成
    ready: {
      type: Boolean,
      default: false,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    // 滚动条
    isDataZoom: {
      type: Boolean,
      default: false
    },
    // 缩放
    zoom: {
      type: Boolean,
      default: false
    },
    // 排序
    isSort: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    // 监听图表数据变化
    eBarData: {
      handler(newVal) {
        if (this.ready) {
          this.chart.setOption(newVal)
        }
      },
      deep: true
    }
  },
  components: {},
  data() {
    return {
      // 图表实例
      chart: null,
      // 图表配置项
      chartOption: {
        // xAxis: {
        //   type: 'category',
        //   data: [],
        //   axisLine: {
        //     lineStyle: {
        //       color: '#E5E5E5'
        //     }
        //   },
        //   axisLabel: {
        //     color: '#666'
        //   },
        //   axisTick: {
        //     show: false
        //   }
        // },
        dataZoom: {
          show: false,
          type: 'slider', // 单独滚动条
          filterMode: 'none', // 不过滤数据 - 保证 y 轴数据范围不变 filter
          brushSelect: true,
          height: 5,
          start: 30,
          end: 75,
          left: 100,
          right: 40,
          bottom: 30,
          backgroundColor: 'transparent',
          // 选中范围的填充颜色
          fillerColor: 'transparent',
          borderWidth: 0,
          borderColor: 'transparent',
          dataBackground: {
            lineStyle: {
              color: 'transparent'
            },
            areaStyle: {
              color: 'transparent'
            }
          },
          selectedDataBackground: {
            lineStyle: {
              color: 'transparent'
            },
            areaStyle: {
              color: 'transparent'
            }
          },

          startValue: 0,
          endValue: 18,
          xAxisIndex: [0],
          showDetail: false,

          handleSize: '0%',
          // 移动手柄尺寸高度
          // 测试发现手柄颜色和边框颜色会出现 偏差，所有设置手柄高度为0, 添加边框高度。由边框撑起高度
          moveHandleSize: 0, // 设置拖动手柄高度为0，只由边框负责高度展示
          // 不展示拖动手柄图标
          moveHandleIcon: 'none',
          moveHandleStyle: {
            borderColor: '#aaaa',
            borderWidth: 5, // 设置边框高度
            borderType: 'solid',
            borderCap: 'round',
            // 保证拖动手柄右边框结尾有圆角
            borderJoin: 'round'
          },
          // 拖动高亮时设置
          emphasis: {
            moveHandleStyle: {
              borderColor: '#aaaa',
              borderWidth: 5,
              borderType: 'solid',
              borderCap: 'round'
            }
          }
        },
        // 添加鼠标滚轮控制左右滑动
        // {
        //   type: 'inside',
        //   zoomOnMouseWheel: false, // 滚轮是否触发缩放
        //   moveOnMouseMove: true, // 鼠标滚轮触发滚动
        //   moveOnMouseWheel: true
        // }
        // dataZoom: {
        //   // show:true,
        //   realtime: true,
        //   type: 'slider',
        //   // y:70,
        //   // width:"90%",
        //   height: 5,
        //   start: 20,
        //   end: 80,
        //   left: 100,
        //   right: 50,
        //   bottom: 30,
        //   textStyle: false,
        //   // zoomLock: true,
        //   // containLabel: true
        //   //----------- 以下是新增 -----------
        //   maxValueSpan: 8,
        //   show: true,
        //   borderColor: 'transparent',
        //   borderCap: 'round',
        //   xAxisIndex: [0],
        //   fillerColor: 'rgba(27,90,169,1)',
        //   handleIcon: 'path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5M36.9,35.8h-1.3z M27.8,35.8 h-1.3H27L27.8,35.8L27.8,35.8z',// 画一个圆形
        //   handleSize: '0%',
        //   moveHandleIcon: 'none', // 不展示拖动手柄图标
        //   handleStyle: {
        //     color: 'rgba(27,90,169,1)',
        //     borderWidth: 0
        //   },
        //   backgroundColor: 'rgba(37, 46, 100, 0)', //两边未选中的滑动条区域的颜色
        //   showDataShadow: false, //是否显示数据阴影 默认auto
        //   showDetail: false, //即拖拽时候是否显示详细数值信息 默认true
        //   filterMode: 'none' // 不过滤数据 - 保证 y 轴数据范围不变  //filter
        // },
        yAxis: {
          type: 'value',
          nameTextStyle: {
            color: '#666666'
            //   padding: [0, 0, 0, 50]
          },
          nameGap: 25,
          axisLine: {
            lineStyle: {
              color: '#E5E5E5'
            }
          },
          axisLabel: {
            color: '#666666'
          },
          splitLine: {
            lineStyle: {
              color: '#E5E5E5',
              type: 'dashed'
            }
          },
          axisTick: {
            show: false
          }
        },
        series: [],
        grid: {
          top: '50',
          right: '40',
          bottom: '50',
          left: '30',
          containLabel: true
        }
      },
      start: 0,
      end: 100,
      num: 10
    }
  },
  methods: {
    sortData(order) {
      var seriesData = this.eBarData.data[0].data
      if (this.eBarData.isObject) {
        const newKey = Object.keys(seriesData).sort((a, b) => {
          if (order === 'asc') {
            return seriesData[a].value - seriesData[b].value
          } else {
            return seriesData[b].value - seriesData[a].value
          }
        })
        let newArr = []
        let xAxisName = []
        newKey.forEach(item => {
          newArr.push({
            id: seriesData[item].id,
            value: seriesData[item].value
          })
          xAxisName.push(this.eBarData.xAxis.data[item])
        })
        this.chart.setOption({
          xAxis: {
            data: xAxisName
          },
          series: [
            {
              data: newArr
            }
          ]
        })
      } else {
        const newKey = Object.keys(seriesData).sort((a, b) => {
          if (order === 'asc') {
            return seriesData[a] - seriesData[b]
          } else {
            return seriesData[b] - seriesData[a]
          }
        })
        let newArr = []
        let xAxisName = []
        newKey.forEach(item => {
          newArr.push(seriesData[item])
          xAxisName.push(this.eBarData.xAxis.data[item])
        })
        this.chart.setOption({
          xAxis: {
            data: xAxisName
          },
          series: [
            {
              data: newArr
            }
          ]
        })
        //   if (order === 'asc') {
        //     seriesData.sort(function(a, b) {
        //       return a - b
        //     })
        //   } else if (order === 'desc') {
        //     seriesData.sort(function(a, b) {
        //       return b - a
        //     })
        //   }
        //   console.log(seriesData,'seriesData');
        //   this.chart.setOption({
        //   series: [
        //     {
        //       data: seriesData
        //     }
        //   ]
        // })
      }
    },
    zoomIn() {
      this.start = this.start >= 40 ? 40 : this.start + this.num
      this.end = this.end <= 70 ? 60 : this.end - this.num
      this.chart.dispatchAction({
        type: 'dataZoom',
        start: this.start,
        end: this.end
      })
    },
    zoomOut() {
      // console.log(this.start,this.end);
      this.start = this.start <= 0 ? (this.start = 0) : this.start - this.num
      if (this.end >= 100) {
        this.end = 100
      } else {
        this.end += this.num
      }
      this.chart.dispatchAction({
        type: 'dataZoom',
        start: this.start,
        end: this.end
      })
      if (this.start <= 10 && this.end >= 90) {
        this.eBarData.data.forEach(item => {
          item.label = {
            show: false
          }
        })
        this.eBarData.dataZoom.start = this.start
        this.eBarData.dataZoom.end = this.end
      }
    },
    /**
     * @description: 设置图表
     * @param {void}
     * @return {void}
     */
    setChart() {
      if (!this.id) {
        return
      }
      var chartDom = document.getElementById(this.id)
      this.chart = this.$echarts.init(document.getElementById(this.id))
      // console.log(this.eBarData);
      // 设置选项
      const { name, xAxis, useUnit, data, dataZoom, color, legend, tooltip, onClick, isBar, isBarWidth } = this.eBarData
      let option = this.$clone(this.chartOption)
      if (isBar == 1) {
        option = {
          title: {
            text: '暂无柱状图数据',
            x: 'center',
            y: 'center',
            textStyle: {
              fontSize: 14,
              fontWeight: 100,
              color: '#333'
            }
          }
        }
      } else {
        option.color = color
        option.xAxis = xAxis
        option.yAxis.name = name
        data[0].data.length > 7 ? (option.dataZoom = this.isDataZoom ? this.chartOption.dataZoom : { show: false }) : (option.dataZoom = null)
        this.start = data[0].data.length > 7 ? option.dataZoom.start * 1 : 0
        this.end = data[0].data.length > 7 ? option.dataZoom.end * 1 : 100
        option.legend = legend
        option.legend.left = legend.left ? legend.left : '15%'
        option.legend.top = legend.top ? legend.top : '2%'
        const series = data.map((el,index) => {
          el.label = {
            show: true,
            position: 'top',
            distance:index == 1 ? 0.5: 5,
            fontSize: 10
          }
          
          el.itemStyle = {
            normal: {
              barBorderWidth: 0.1 // 将柱子的边界线宽度设置为 0.5px
            }
          }
          ;(el.barWidth = isBarWidth && el.data.length > 7 ? '30' : '20'), (el.barGap = isBarWidth && el.data.length > 7 ? '30%' : '50%'), (el.barCategoryGap = isBarWidth && el.data.length > 7 ? '10%' : '20%')
          return el
        })
        option.tooltip = tooltip ? tooltip: { // 鼠标移入提示
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              textStyle: {
                fontSize: 12
              },
              formatter: function(params) {
                let title = ''
                params.forEach(item => {
                  title += item.seriesName + ':    ' + item.value + name + '<br/>'
                })
                return params[0].name + '<br/>' + title
              }
            }
        onClick && this.chart.on('click', onClick)
        option.series = series
      }

      this.chart.setOption(option, true)
      this.chart.on('dataZoom', params => {
        var zoomRange = params.start
        var zoomEnd = params.end
        this.chart.setOption({
          dataZoom: {
            show: zoomRange >= 20 || zoomEnd <= 80 ? true : false
          },
          series: [
            {
              label: {
                show: zoomRange <= 20 && zoomEnd >= 80 ? false : true, // 当视图区域是全部数据时显示标签
                fontSize: zoomRange <= 30 && zoomEnd >= 50 ? 10 : 12
              },
              barWidth: zoomRange <= 20 && zoomEnd >= 70 ? 15 : 30,
              barGap: zoomRange < 20 && zoomEnd > 60 ? '10%' : '30%',
              barCategoryGap: zoomRange < 20 && zoomEnd > 60 ? '10%' : '20%'
            },
            {
              label: {
                show: zoomRange <= 20 && zoomEnd >= 80 ? false : true, // 当视图区域是全部数据时显示标签
                fontSize: zoomRange <= 30 && zoomEnd >= 50 ? 10 : 12
              },
              barWidth: zoomRange <= 20 && zoomEnd >= 70 ? 15 : 30,
              barGap: zoomRange < 20 && zoomEnd > 60 ? '10%' : '30%',
              barCategoryGap: zoomRange < 20 && zoomEnd > 60 ? '10%' : '20%'
            },
            {
              label: {
                show: zoomRange <= 20 && zoomEnd >= 80 ? false : true, // 当视图区域是全部数据时显示标签
                fontSize: zoomRange <= 30 && zoomEnd >= 50 ? 10 : 12
              },
              barWidth: zoomRange <= 20 && zoomEnd >= 70 ? 15 : 30,
              // barWidth: zoomRange <= 20 && zoomEnd >= 60 ? 15 : 20,
              barGap: zoomRange < 20 && zoomEnd > 60 ? '10%' : '30%',
              barCategoryGap: zoomRange < 20 && zoomEnd > 60 ? '10%' : '20%'
            }
          ]
        })
      })
      let changeSize = elementResizeDetectorMaker()
      let _this = this
      changeSize.listenTo(chartDom, () => {
        //chartDom为之前获取到的容器名
        _this.$nextTick(() => {
          this.chart.resize()
        })
      })
    }
  },
  watch: {
    ready: {
      handler(newVal, oldVal) {
        if (newVal === true) {
          // console.log(newVal,'newVal');
          // console.log(oldVal,'oldVal');
          setTimeout(() => {
            if (document.getElementById(this.id)) {
              this.$nextTick(() => {
                this.setChart()
              })
            }
          }, 50)
        }

        //
      },
      deep: true,
      immediate: true
    }
  }
  // beforeDestroy() {
  //   // 销毁实例
  //   this.chart.dispose()
  //   removeEventListener('resize', this.resize)
  // }
}
</script>

<style lang="less" scoped>

.e-bar {
  height: 300px;
  width: 100%;
}
.zoom {
  position: absolute;
  top: -22px;
  right: 21px;

  .zoom-btn {
    width: 25px;
    height: 25px;
    text-align: center;
    margin-right: 5px;
    font-size: 15px;
    color: #fff;
    background-color: #9f9696;
    padding: 0;
  }
}
.sort {
  position: absolute;
  top: -25px;
  right: 90px;
  display: flex;
  flex-direction: column;
  font-size: 15px;
  color: #9f9696;
}
</style>
